package cookie;

import utils.CookieUtils;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * cookie练习
 */
public class C8_CookieLoginOk extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("C8_CookieLoginOk 被调用...");

        //获取用户名
        String username = req.getParameter("username");
        //新建cookie
        Cookie cookie = new Cookie("username", username);
        //设置cookie生命周期 3天
        cookie.setMaxAge(60 * 60 * 24 * 30);

        //保存到浏览器
        resp.setContentType("text/html;charset=utf-8");
        resp.addCookie(cookie);
        PrintWriter writer = resp.getWriter();
        writer.print("<h1>登录成功</h1>");
        writer.flush();
        writer.close();
    }
}
